package com.spic.business.alarm.service.impl;

import com.spic.business.alarm.config.Device;
import com.spic.business.alarm.config.ProjectConfig;
import com.spic.business.alarm.config.ProjectInfo;
import com.spic.business.alarm.config.Query;
import com.spic.business.alarm.domain.ResolveData;
import com.spic.business.alarm.domain.SurfDevice;
import com.spic.business.alarm.domain.vo.ProjectData;
import com.spic.business.alarm.mapper.BianPoAlarmDataMapper;
import com.spic.business.alarm.mapper.SurfDeviceMapper;
import com.spic.business.alarm.service.IBianPoAlarmDataService;
import com.spic.business.alarm.utils.JsonFileUtils;
import com.spic.business.common.core.utils.DateUtil;
import com.spic.common.core.utils.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 290512
 * @create 2022-04-09 13:48
 */
@Service
public class BianPoAlarmDataServiceImpl implements IBianPoAlarmDataService
{
    @Autowired
    public SurfDeviceMapper deviceMapper;

    @Autowired
    private BianPoAlarmDataMapper bianPoAlarmDataMapper;

    private static final Logger log = LoggerFactory.getLogger(BianPoAlarmDataServiceImpl.class);

    public Map<String,String> bpAlarmRemark(String dayType){
        Map<String,String> map = new HashMap<>();
        List<Map<String, Object>> list = queryDataList(null, dayType);
        map.put("remark","边坡位移稳定!");

        List<Map<String, Object>> list2d = list.stream().filter(item ->
                Double.parseDouble(item.get("2D").toString())>=30).collect(Collectors.toList());
        List<Map<String, Object>> listz = list.stream().filter(item ->
                Double.parseDouble(item.get("Z").toString())>=30).collect(Collectors.toList());
        if(list2d.size()>0){
            map.put("remark","边坡小时累计水平位移超过30毫米, 风险预警!");
        }
        if(listz.size()>0){
            map.put("remark","边坡小时累计下沉位移超过30毫米, 风险预警!");
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> queryDataList(String gpsType,String dayType)
    {
        ProjectInfo projectInfo = JsonFileUtils.getProjectConfig();
        List<ProjectConfig> projectConfigList = projectInfo.getProjects();
        DateTime now = new DateTime();
        Date endTime = now.toDate();

        LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点

        String td_st_str =today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Date date1 =new Date();
        Date date = new Date();

        if("today".equals(dayType)){
            //实际数据
//            date1 = DateUtil.format(td_st_str,"yyyy-MM-dd HH:mm:ss"); //今天的零点
//            date = endTime; //现在时间

            //测试数据
            date1 = DateUtil.format("2022-04-20 00:00:00"); //今天的零点
            String mm1 = DateUtil.format(new Date(), "HH:mm:ss");
            date = DateUtil.format("2022-04-20 "+mm1);

        }else if("yesterday".equals(dayType)){

            LocalDateTime yest_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).minusDays(1);
            String yestStartTime =yest_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime yest_end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).minusDays(1);//当天零点
            String yestEndTime =yest_end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            //实际数据
//            date1 = DateUtil.format(yestStartTime,"yyyy-MM-dd HH:mm:ss"); //昨天的零点
//            date = DateUtil.format(yestEndTime,"yyyy-MM-dd HH:mm:ss"); //昨天的最大点

            //测试数据
            date1 = DateUtil.format("2022-04-19 00:00:00");
            date = DateUtil.format("2022-04-19 23:59:59");
        }

        for (ProjectConfig projectConfig : projectConfigList)
        {
            if(projectConfig.getProjectId()==2){
                return initData(projectConfig, date1, date,gpsType);
            }
        }
        return null;
    }

    private List<Map<String, Object>>  initData(ProjectConfig projectConfig, Date startTime, Date endTime,String gpsType) {
        ProjectData projectData = new ProjectData();
        Query query = new Query();
        List<Device> devices = projectConfig.getDevices();
        if (devices == null || devices.size() == 0) {
            log.warn("");
            return null;
        }
        //定义 请求的是哪个 1获取gps数据  2 告警提醒数据
        int type = 0;
        List<String> deviceIdList = (List<String>)projectConfig.getDevices().stream().map(Device::getId).collect(Collectors.toList());
        String join = String.join("','", (Iterable) deviceIdList);
        query.setSensorIdList("'"+join+"'");
        if(StringUtils.isEmpty(gpsType)){
            List<SurfDevice> surfDevices = deviceMapper.queryDataDeviceNameList(query);
            List<String> collect = surfDevices.stream().map(SurfDevice::getDevicename).collect(Collectors.toList());
            String deviceNameStr = String.join("','", (Iterable) collect);
            query.setGpsType("'"+deviceNameStr+"'");
            type = 2;
        }else{
            query.setGpsType("'"+gpsType+"'");
            type = 1;
        }
        query.setStartTime(startTime);
        query.setEndTime(endTime);
        List<SurfDevice> deviceList = this.deviceMapper.queryDataList(query);
        List<ResolveData> resolvedDataList = this.bianPoAlarmDataMapper.queryDataList(query);
        if (deviceList == null || deviceList.size() == 0) {
            log.error("");
            return null;
        }

        resolvedDataList.forEach(data -> {
            if(data==null){
                data = new ResolveData();
            }
            Optional<SurfDevice> optionalSurfDevice = deviceList.stream().findFirst();
            if (optionalSurfDevice.isPresent()) {
                SurfDevice surfDevice = optionalSurfDevice.get();
                data.setDevice(surfDevice);
            }
        });

        projectData.setDeviceList(deviceList);
        projectData.setResolveDataList(resolvedDataList);
        List<Map<String, Object>> list = resolvedDataFileContentCreate(projectConfig, projectData,type);
        return list;
    }

    public static List<Map<String,Object>> resolvedDataFileContentCreate(ProjectConfig config, ProjectData projectData,int type) {
        List<ResolveData> resolveDataList = projectData.getResolveDataList();
        if(type==1){
            List <ResolveData> collect= resolveDataList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ResolveData::getHH))), ArrayList::new));
            List<Map<String, Object>> list = returnListMap(collect);
            return list;
        }else if (type == 2){
            List<Map<String,Object>> listMap = new ArrayList<>();
//            Map<Pair<String, String>, Long> collect1 = resolveDataList.stream().collect(Collectors.groupingBy(p -> Pair.of(p.getDevicename(), p.getHH()), Collectors.counting()));
            Map<String, Map<String, List<ResolveData>>> collect1 = resolveDataList.stream().collect(Collectors.groupingBy(ResolveData::getDevicename, Collectors.groupingBy(ResolveData::getHH)));
            Set<String> keySet = collect1.keySet();
            for(Iterator<String> it = keySet.iterator();it.hasNext();) {
                List<ResolveData> resolveData = new ArrayList<>();
                String key = it.next();
                Map<String,List<ResolveData>> map = collect1.get(key);
                Set<Map.Entry<String, List<ResolveData>>> entrySet = map.entrySet();
                for(Iterator<Map.Entry<String, List<ResolveData>>> it2 = entrySet.iterator();it2.hasNext();) {
                    Map.Entry<String, List<ResolveData>> next = it2.next();
                    List<ResolveData> value = next.getValue();
                    resolveData.addAll(value);
                }
                listMap.addAll(returnListMap(resolveData));
            }
            return listMap;
        }
//        List<Map<String, Object>> timeFilter = listMap.stream().filter(f -> (Integer.parseInt(f.get("time") + "") % 2 == 0)).collect(Collectors.toList());
        return null;
    }

    private  static  List<Map<String,Object>> returnListMap( List <ResolveData> collect){
        List<Map<String,Object>> listMap = new ArrayList<>();
        for (int i = 0; i < collect.size(); i++)
        {
            ResolveData resolveData1 = collect.get(i);
            double V1 =  Double.parseDouble((resolveData1.getV1() == null) ? "0" : resolveData1.getV1().setScale(3, 4).toString());
            double V2 =  Double.parseDouble((resolveData1.getV2() == null) ? "0" : resolveData1.getV2().setScale(3, 4).toString());
            double V3 =  Double.parseDouble((resolveData1.getV3() == null) ? "0" : resolveData1.getV3().setScale(3, 4).toString());

            for(int j = i+1; j <  collect.size() ; j++) {
                ResolveData resolveData2  = collect.get(j);
                double V11 =  Double.parseDouble((resolveData2.getV1() == null) ? "0" : resolveData2.getV1().setScale(3, 4).toString());
                double V22 =  Double.parseDouble((resolveData2.getV2() == null) ? "0" : resolveData2.getV2().setScale(3, 4).toString());
                double V33 =  Double.parseDouble((resolveData2.getV3() == null) ? "0" : resolveData2.getV3().setScale(3, 4).toString());

                Map<String,Object> m = new HashMap<>();
                double formatX =  V11 - V1;
                double formatY = V22 - V2;
                double formatZ = V33-V3;
                double hypot2D = Math.hypot(V11 - V1, V22 - V2);
                double hypot3D = Math.hypot(hypot2D, formatZ);

                m.put("X",String.format("%.3f",formatX));
                m.put("Y",String.format("%.3f",formatY));
                m.put("Z",String.format("%.3f",formatZ));
                m.put("2D",String.format("%.3f",hypot2D));
                m.put("3D",String.format("%.3f",hypot3D));
                m.put("time",resolveData2.getHH());
                m.put("deviceName",resolveData2.getDevicename());
                listMap.add(m);
                break;
            }
        }
        return listMap;
    }

    public static void main(String[] args) {

        int array[] = {4,5,3,7};
        int result = 0;
        int length = array.length;
        for(int i = 0 ; i < length; i++) {
            int a = array[i];
            for(int j = i+1; j < length ; j++) {
                int b = array[j];
                result = (b-a);
                System.out.println(result);
                break;
            }
        }

        System.out.println(55.99999d-44.33333d);

        double hypot = Math.hypot(3, 4);
        System.out.println(hypot);
    }

}
